package com.wymobilearchitecture.study.thread.use;


import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import androidx.annotation.NonNull;

import com.example.w_library.log.WLog;

/**
 * 适用于主线程和工作线程通信,适用于持续性任务,比如轮询的场景,所有任务串行执行
 * 缺点:不会想普通线程一样主动销毁资源,会一直运行着,所以可能会造成内存泄露
 */
public class HandlerThreadTest {

    private int MSG_WHAT_1 = 1;
    public HandlerThreadTest() {

        handlerThread();

        looperThread();
    }

    private void handlerThread(){

        HandlerThread handlerThread = new HandlerThread("handler-thread");
        handlerThread.start();

        //适用于主线程需要和子线程通讯的场景
        //应用于持续性任务,比如轮询
        MyHandler myHandler =new MyHandler(handlerThread.getLooper());
        myHandler.sendEmptyMessage(MSG_WHAT_1);

        //结束线程
        handlerThread.quitSafely();
    }

    static class MyHandler extends Handler {

        public MyHandler(Looper looper){
            super(looper);

        }
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            WLog.e("handleMessage: " + msg.what);
            WLog.e("handleMessage: " + Thread.currentThread().getName());

        }
    }


    /**
     * HandleThread 内部实现
     */
    private void looperThread(){
        LooperThread looperThread = new LooperThread("looper-thread");
        looperThread.start();
        Handler looperThreadHandler  = new Handler(looperThread.getLooper()){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                WLog.e("looperThread: " + msg.what);
                WLog.e("looperThread: " + Thread.currentThread().getName());
            }
        };
        looperThreadHandler.sendEmptyMessage(1);
    }

    static class LooperThread extends Thread{

        public LooperThread(String name){
            super(name);
        }

        private Looper looper;
        public Looper getLooper() {
            synchronized (this){
                if (looper == null && isAlive()){
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            return looper;
        }

        @Override
        public void run() {
            super.run();
            Looper.prepare();
            synchronized (this){
                looper = Looper.myLooper();
                notify();
            }
            Looper.loop();
        }
    }


}
